package com.zzyl.nursing.service.impl;

import java.util.HashMap;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baidubce.qianfan.Qianfan;
import com.baidubce.qianfan.util.Json;
import com.zzyl.common.constant.Constants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.QianFangAIModuleUtil;
import com.zzyl.framework.web.service.TokenService;
import com.zzyl.nursing.dto.UserLoginRequestDto;
import com.zzyl.nursing.service.WeChatService;
import com.zzyl.nursing.vo.LoginVo;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.FamilyMemberMapper;
import com.zzyl.nursing.domain.FamilyMember;
import com.zzyl.nursing.service.IFamilyMemberService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

/**
 * 老人家属Service业务层处理
 *
 * @author ruoyi
 * @date 2025-02-25
 */
@Service
public class FamilyMemberServiceImpl extends ServiceImpl<FamilyMemberMapper, FamilyMember> implements IFamilyMemberService {
    @Autowired
    private FamilyMemberMapper familyMemberMapper;

    @Autowired
    private QianFangAIModuleUtil qianFangAIModuleUtil;

    @Autowired
    private WeChatService weChatService;
    @Value("${token.secret}")
    private String secret;

    @Autowired
    private TokenService tokenService;

    /**
     * 查询老人家属
     *
     * @param id 老人家属主键
     * @return 老人家属
     */
    @Override
    public FamilyMember selectFamilyMemberById(Long id) {
        return getById(id);
    }

    /**
     * 查询老人家属列表
     *
     * @param familyMember 老人家属
     * @return 老人家属
     */
    @Override
    public List<FamilyMember> selectFamilyMemberList(FamilyMember familyMember) {
        return familyMemberMapper.selectFamilyMemberList(familyMember);
    }

    /**
     * 新增老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int insertFamilyMember(FamilyMember familyMember) {
        return save(familyMember) ? 1 : 0;
    }

    /**
     * 修改老人家属
     *
     * @param familyMember 老人家属
     * @return 结果
     */
    @Override
    public int updateFamilyMember(FamilyMember familyMember) {
        return updateById(familyMember) ? 1 : 0;
    }

    /**
     * 批量删除老人家属
     *
     * @param ids 需要删除的老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除老人家属信息
     *
     * @param id 老人家属主键
     * @return 结果
     */
    @Override
    public int deleteFamilyMemberById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    /**
     * 用户登录
     *
     * @param userLoginRequestDto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto userLoginRequestDto) {
        //调用WeService接口
        String openId = this.weChatService.getOpenId(userLoginRequestDto.getCode());
        //判断是为空
        if (ObjectUtil.isEmpty(openId)) {
            throw new BaseException("认证失败");
        }
        //去数据库查询是否有该用户
        FamilyMember familyMember = this.lambdaQuery().eq(FamilyMember::getOpenId, openId).one();
        //为空则新增，不为空则修改
        if (ObjectUtil.isNull(familyMember)) {
            familyMember = new FamilyMember();
            familyMember.setOpenId(openId);
        }
        //获取手机号码
        String phoneNumber = this.weChatService.getPhoneNumber(userLoginRequestDto.getPhoneCode());
        //为空则新增用户，不为空则修改用户
        if (ObjectUtil.isEmpty(phoneNumber)) {
            throw new BaseException("查无此手机号码");
        }
        familyMember.setPhone(phoneNumber);
        //进入数据库进行修改数据
        addOrUpdateFamilyMember(familyMember);
        //新建claims集合对象
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.NICKNAME, familyMember.getName());
        claims.put("id", familyMember.getId());
        //生成token
//        String token = Jwts.builder()
//                .setClaims(claims)
//                .signWith(SignatureAlgorithm.HS512, secret)
//                .compact();
        String token = tokenService.createToken(claims);

        return LoginVo.builder()
                .nickName(familyMember.getName())
                .token(token)
                .build();
    }

    /**
     * 新增或者修改用户数据
     *
     * @param familyMember
     */
    private void addOrUpdateFamilyMember(FamilyMember familyMember) {
        //判断是第一次还是之前就登过
        if (ObjectUtil.isNotNull(familyMember.getId())) {
            //能拿到id就说明之前就已经登录过了,则进行更新
            updateById(familyMember);
            return;
        }
        //利用千帆AI大模
        String name = this.qianFangAIModuleUtil.invoke("帮我生成一个微信用户的中文名称,随机即可,字数在6-9之间");
//        String nickName = JSONUtil.toBean(name, String.class);
        String string = JSONUtil.toJsonStr(name);
        String[] split = string.split("\"中文名称\": \"");
        String nickname = split[1];
        String nickName = nickname.split("\"")[0];
        familyMember.setName(nickName);
        this.save(familyMember);
    }
}
